/**   
 * @Title: ImageDB.java 
 * @Package com.esun.util.img.db 
 * @Description: 存储图片的数据库 
 * @author Miko baoz@500wan.com   
 * @date 2011-3-24 下午07:42:03  
 */
package com.esun.util.img.db;

import java.io.ByteArrayOutputStream;

import com.esun.util.log.EDebug;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;

/**
 * @ClassName: ImageDB
 * @Description: 存储图片的数据库
 * @author Miko baoz@500wan.com
 * @date 2011-3-24 下午07:42:03
 * 
 */
public class ImageDB {

	// DataBase 信息
	private static final String DBNAME = "db_500wan";
	private static final String TABLENAME = "image";

	// 数据表 各列 名称定义
	private static final String ID = "_id";
	private static final String NAME = "name";
	private static final String IMG = "img";

	// 数据表创建语句
	private static final String CREAT_TABLE = "CREATE TABLE " + TABLENAME + "(" + ID + " INTEGER PRIMARY KEY," + NAME + " TEXT," + IMG + " BLOB)";

	// 声明db对象
	private SQLiteDatabase db;

	private static ImageDB imageDB = null;

	public static ImageDB getImageDB() {

		if (imageDB == null) {
			return imageDB = new ImageDB();
		} else {
			return imageDB;
		}
	}

	// 打开数据库
	public void open(Context context) {
		db = context.openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		if (!(isTableExits(TABLENAME))) {
			db.execSQL(CREAT_TABLE);
		}
	}

	// 关闭数据库
	public void close() {
		try {
			db.close();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	// 获取数据库中第一行内容的ID
	public String getFirstLine() {

		Cursor cur;
		cur = db.query(TABLENAME, new String[] { ID, NAME, IMG }, null, null, null, null, null);
		cur.moveToFirst();

		return cur.getString(cur.getColumnIndex(ID));
	}

	// 数据库中是否存在该内容
	public boolean isExist(String name) {

		String sql = "SELECT " + NAME + " FROM " + TABLENAME + " WHERE " + NAME + "='" + name + "'";

		Cursor cur;
		cur = db.rawQuery(sql, null);
		int count = cur.getCount();
		cur.close();

		if (count > 0) {
			return true;
		} else {
			return false;
		}
	}

	// 得到数据
	public byte[] getData(String name) {

		String sql = "SELECT " + IMG + " FROM " + TABLENAME + " WHERE " + NAME + "='" + name + "'";

		Cursor cur;
		cur = db.rawQuery(sql, null);

		cur.moveToFirst();

		byte[] in = cur.getBlob(cur.getColumnIndex(IMG));

		return in;
	}

	// 得到数据库中存储的条数
	public int getDBLength() {

		Cursor cur;
		cur = db.query(TABLENAME, new String[] { ID, NAME, IMG }, null, null, null, null, null);

		int result = cur.getCount();
		cur.close();

		return result;
	}

	// 从数据库中删除一个图像
	public boolean deleteImg(String id) {

		EDebug.o(this, "Do delete img id is : " + id);

		try {
			db.delete(TABLENAME, ID + "=?", new String[] { id });
			EDebug.o(this, "Do delete img success : " + id);
		} catch (Exception e) {
			EDebug.o(this, "【删除图片错误，ImageDB.java 137行】");
		}
		return true;
	}

	// 向数据库中添加图像
	public boolean insertImg(String name, Bitmap bmp) {

		ContentValues cv = new ContentValues();
		final ByteArrayOutputStream os = new ByteArrayOutputStream();

		bmp.compress(Bitmap.CompressFormat.PNG, 100, os);

		cv.put(NAME, name);
		cv.put(IMG, os.toByteArray());

		db.insert(TABLENAME, null, cv);

		return true;
	}

	// 更新数据库中的图像
	public boolean updateImg(String name, Bitmap bmp, String oldID) {

		ContentValues cv = new ContentValues();
		final ByteArrayOutputStream os = new ByteArrayOutputStream();

		bmp.compress(Bitmap.CompressFormat.PNG, 100, os);

		cv.put(NAME, name);
		cv.put(IMG, os.toByteArray());

		db.update(TABLENAME, cv, ID + "=", new String[] { oldID });

		return true;
	}

	/**
	 * 判断表是否存在
	 * 
	 * @param tablename
	 * @return true 表存在 ， false 表示不存在
	 * @author Miko
	 */
	private boolean isTableExits(String tablename) {

		boolean result = false;// 表示不存在
		String str = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='" + tablename + "'";
		Cursor c = db.rawQuery(str, null);
		c.moveToFirst();
		int xcount = Integer.parseInt(c.getString(0));
		c.close();
		if (xcount != 0) {
			result = true; // 表存在
		}
		return result;
	}

	public boolean dbIsOpen() {

		return db.isOpen();
	}
}
